package org.darkforest.admin.controller;

import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Multimap;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.annotation.ArchivesLog;
import org.darkforest.common.util.AliOssFileUploadUtil;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.TreeListUtil;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.AdvMapper;
import org.darkforest.dao.mapper.AdvPositionMapper;
import org.darkforest.dao.mapper.ArticleClassMapper;
import org.darkforest.dao.mapper.ArticleMapper;
import org.darkforest.model.Adv;
import org.darkforest.model.AdvBean;
import org.darkforest.model.AdvPosition;
import org.darkforest.model.AdvPositionBean;
import org.darkforest.model.Article;
import org.darkforest.model.ArticleClass;
import org.darkforest.model.Festival;
import org.darkforest.model.GoodsClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("website")
public class ArticleController extends WebController<ArticleController> {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleClassMapper articleClassMapper;

    @Autowired
    private AdvPositionMapper adMapper;

    @Autowired
    private AdvMapper advMapper;

    /**
     * 文章分类列表
     *
     *@param request
     * @return
     */
    @RequestMapping("articleClass")
    public ModelAndView articleClass(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("website/articleClass/list");
        ArticleClass articleClass = new ArticleClass();
        // 改页处理用
        String start = request.getParameter("start");
        if (start != null && !"".equals(start)) {
            articleClass.setStart(Integer.valueOf(start));
        }
        // 不分页
        articleClass.setPageSwitch(false);

        List<ArticleClass> articleClassesList = articleClassMapper.findArticleClassByCondition(articleClass);
        articleClass.setResultList(articleClassesList);
        modelAndView.addObject("page", articleClass);

        // treelist
        TreeListUtil treeListUtil = new TreeListUtil();
        treeListUtil.setArticleClassNodes(articleClassesList);
        List<ArticleClass>  articleClassListTemp = treeListUtil.buildArticleClassTree();
        modelAndView.addObject("listTree", articleClassListTemp);

        return modelAndView;
    }

    /**
     * 文章分类新增
     *
     * @param acParentId
     * @return
     */
    @RequestMapping("articleClass/toAdd")
    public ModelAndView toAddArticleClass(String acParentId) {
        ModelAndView modelAndView = new ModelAndView("website/articleClass/add");
        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcParentId(0);
        List<ArticleClass> articleClassList = articleClassMapper.findArticleClassByCondition(articleClass);
        modelAndView.addObject("articleClassList", articleClassList);
        if (null != acParentId && !"".equals(acParentId)) {
            modelAndView.addObject("acParentId", acParentId);
        }
        // 新增的分类的排序
        modelAndView.addObject("acSort", articleClassMapper.selectNextSort());
        return modelAndView;
    }

    @RequestMapping("articleClass/doAdd")
    @ArchivesLog(operationDescription = "新增文章分类")
    public ModelAndView addArticleClass(HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("msg");
        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcName(request.getParameter("acName"));
        articleClass.setAcCode(request.getParameter("acCode"));
        articleClass.setAcParentId(request.getParameter("acParentId") == null ? 0 : Integer.parseInt(request.getParameter("acParentId")));
        articleClass.setAcSort(Integer.parseInt(request.getParameter("acSort")));

        int i = articleClassMapper.insert(articleClass);
        if (i > 0) {
            modelAndView.addObject("msg", "文章分类新增成功");
        } else {
            modelAndView.addObject("msg", "文章分类新增失败");
        }
        modelAndView.addObject("returnUrl", "website/articleClass");
        return modelAndView;
    }

    /**
     * 文章分类修改
     *
     * @param acId
     * @return
     */
    @RequestMapping("articleClass/toModify")
    public ModelAndView toModifyArticleClass(Integer acId) {
        ModelAndView modelAndView = new ModelAndView("website/articleClass/edit");
        ArticleClass articleClass = this.articleClassMapper.selectByPrimaryKey(acId);
        modelAndView.addObject("articleClass", articleClass);
        return modelAndView;
    }

    @RequestMapping("articleClass/doModify")
    @ArchivesLog(operationDescription = "修改文章分类")
    public ModelAndView doModifyArticleClass(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcId(request.getParameter("acId") == null ? 0 : Integer.parseInt(request.getParameter("acId")));
        articleClass.setAcName(request.getParameter("acName"));
        articleClass.setAcCode(request.getParameter("acCode"));
        articleClass.setAcParentId(request.getParameter("acParentId") == null ? 0 : Integer.parseInt(request.getParameter("acParentId")));
        articleClass.setAcSort(Integer.parseInt(request.getParameter("acSort")));
        int i = articleClassMapper.updateByPrimaryKeySelective(articleClass);
        if (i > 0) {
            modelAndView.addObject("msg", "文章分类修改成功");
        } else {
            modelAndView.addObject("msg", "文章分类修改失败");
        }
        modelAndView.addObject("returnUrl", "website/articleClass");
        return modelAndView;
    }

    /**
     * 文章分类删除
     *
     * @param request
     * @return
     */
    @RequestMapping("articleClass/delete")
    @ArchivesLog(operationDescription = "删除文章分类")
    public ModelAndView delArticleClass(HttpServletRequest request) {
        // request.getParameterValues("acId") = 13,14,16,17
        String[] acIds = request.getParameterValues("acId")[0].split(",");
        int i = 0;
        for (String id : acIds) {
            i += articleClassMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == acIds.length) {
            modelAndView.addObject("msg", "文章分类删除成功");
        } else {
            modelAndView.addObject("msg", "文章分类删除失败");
        }
        modelAndView.addObject("returnUrl", "website/articleClass");
        return modelAndView;
    }

    /**
     * 文章分类名称检查是否重复
     *
     * @param articleClass
     * @return
     */
    @RequestMapping("articleClass/checkArticleClassName")
    public @ResponseBody boolean checkArticleClassName(ArticleClass articleClass) {
        List<ArticleClass> articleClassList = articleClassMapper.findCheckArticleClassNamesByCondition(articleClass);
        if (articleClassList.size() == 0) {
            return true;
        }
        // 修改时
        if (articleClassList.size() == 1) {
            // 修改的当前记录的数据时
            if (articleClassList.get(0).getAcId() == articleClass.getAcId()) {
                return true;
            }
        }
        // 添加时 或  修改的其他记录的数据时
        return false;
    }

    /**
     * 文章列表
     *
     * @param request
     * @return
     */
    @RequestMapping("article")
    public ModelAndView article(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("website/article/list");

        // 检索条件
        String articleTitle = request.getParameter("articleTitle");
        String acId = request.getParameter("acId");
        // 改页处理用
        String start = request.getParameter("start");

        Article article = new Article();
        if (acId != null && !acId.equals("")) {
            article.setAcId(Integer.parseInt(acId));
        }
        article.setArticleTitle(articleTitle);
        // 改页处理时
        if (start != null && !"".equals(start)) {
            article.setStart(Integer.valueOf(start));
        }

        article.setResultList(articleMapper.findArticleByCondition(article));
        modelAndView.addObject("page", article);

        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcParentId(0);
        List<ArticleClass> articleClassParentList = articleClassMapper.findArticleClassByCondition(articleClass);
        modelAndView.addObject("articleClassParentList", articleClassParentList);
        List<ArticleClass> articleClassSonList = articleClassMapper.findArticleClassSonByCondition();
        modelAndView.addObject("articleClassSonList", articleClassSonList);

        return modelAndView;
    }

    /**
     * 文章增加
     *
     * @return
     */
    @RequestMapping("article/toAdd")
    public ModelAndView articleAdd() {
        ModelAndView modelAndView = new ModelAndView("website/article/add");
        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcParentId(0);
        List<ArticleClass> articleClassParentList = articleClassMapper.findArticleClassByCondition(articleClass);
        modelAndView.addObject("articleClassParentList", articleClassParentList);
        List<ArticleClass> articleClassSonList = articleClassMapper.findArticleClassSonByCondition();
        modelAndView.addObject("articleClassSonList", articleClassSonList);
        // 新增的文章的排序
        modelAndView.addObject("articleSort", articleMapper.selectNextSort());
        return modelAndView;
    }

    @RequestMapping("article/doAdd")
    @ArchivesLog(operationDescription = "新增文章")
    public ModelAndView doAddArticle(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        String  articleTitle =  request.getParameter("articleTitle");
        Integer acId = Integer.parseInt(request.getParameter("acId"));
        // 标题和所属分类重复CHECK的处理
        boolean isExist = false;
        List<Article> articleList = articleMapper.selectAllArticle();
        for (Article articleDB : articleList) {
            if (articleTitle.equals(articleDB.getArticleTitle()) && acId == articleDB.getAcId() ) {
                isExist = true;
                break;
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "文章新增失败：新增后的所属分类内该标题已经存在");
            // returnUrl不设定时，返回到修改页面
            return modelAndView;
        }

        // 没有重复时，更新数据库
        Article article = new Article();
        article.setAcId(acId);
        article.setArticleTitle(articleTitle);
        article.setArticleUrl(request.getParameter("articleUrl"));
        article.setArticleContent(request.getParameter("articleContent"));
        String sort = request.getParameter("articleSort");
        article.setArticleSort((sort == null || StringUtils.isEmpty(sort)) ? 99 : Integer.parseInt(sort));
        article.setArticleShow(request.getParameter("articleShow").equals("1") ? true : false);
        String[] articlePictures = request.getParameterValues("articlePicture");
        String articlePicture = null;
        if (articlePictures != null && articlePictures.length > 0) {
            for (int i = 0; i < articlePictures.length; i++) {
                if (i == 0) {
                    articlePicture = articlePictures[i];
                } else {
                    articlePicture += "," + articlePictures[i];
                }
            }
        }
        article.setArticlePicture(articlePicture);
        article.setArticleTime(DateUtil.unixTimeStampInt().intValue());
        int i = articleMapper.insert(article);
        if (i > 0) {
            modelAndView.addObject("msg", "文章新增成功");
        } else {
            modelAndView.addObject("msg", "文章新增失败");
        }
        modelAndView.addObject("returnUrl", "website/article");
        return modelAndView;
    }

    /**
     * 文章修改
     *
     * @param articleId
     * @return
     */
    @RequestMapping("article/toModify")
    public ModelAndView toModifyArticle(Integer articleId) {
        ModelAndView modelAndView = new ModelAndView("website/article/edit");
        Article article = this.articleMapper.selectByPrimaryKey(articleId);
        modelAndView.addObject("article", article);
        if (article.getArticlePicture() != null) {
            List<String> articlePictures = new ArrayList<String>();
            for (int i = 0; i < article.getArticlePicture().split(",").length; i++) {
                articlePictures.add(article.getArticlePicture().split(",")[i]);
            }
            modelAndView.addObject("articlePictures", articlePictures);
        }
        ArticleClass articleClass = new ArticleClass();
        articleClass.setAcParentId(0);
        List<ArticleClass> articleClassParentList = articleClassMapper.findArticleClassByCondition(articleClass);
        modelAndView.addObject("articleClassParentList", articleClassParentList);
        List<ArticleClass> articleClassSonList = articleClassMapper.findArticleClassSonByCondition();
        modelAndView.addObject("articleClassSonList", articleClassSonList);
        modelAndView.addObject("acId", article.getAcId());
        return modelAndView;
    }

    @RequestMapping("article/doModify")
    @ArchivesLog(operationDescription = "修改文章")
    public ModelAndView doModifyArticle(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        String  articleTitle =  request.getParameter("articleTitle");
        Integer acId = Integer.parseInt(request.getParameter("acId"));
        Integer articleId = Integer.parseInt(request.getParameter("articleId"));
        // 标题和所属分类重复CHECK的处理
        boolean isExist = false;
        List<Article> articleList = articleMapper.selectAllArticle();
        for (Article articleDB : articleList) {
            if (articleId != articleDB.getArticleId()) {
                if (articleTitle.equals(articleDB.getArticleTitle()) && acId == articleDB.getAcId() ) {
                    isExist = true;
                    break;
                }
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "文章修改失败：修改后的所属分类内该标题已经存在");
            // returnUrl不设定时，返回到修改页面
            return modelAndView;
        }

        // 没有重复时，更新数据库
        Article article = new Article();
        article.setArticleId(articleId);
        article.setAcId(acId);
        article.setArticleTitle(articleTitle);
        article.setArticleUrl(request.getParameter("articleUrl"));
        article.setArticleContent(request.getParameter("articleContent"));
        article.setArticleSort(Integer.parseInt(request.getParameter("articleSort")));
        article.setArticleShow(request.getParameter("articleShow").equals("1") ? true : false);
        String[] articlePictures = request.getParameterValues("articlePicture");
        String articlePicture = null;
        if (articlePictures != null && articlePictures.length > 0) {
            for (int i = 0; i < articlePictures.length; i++) {
                if (i == 0) {
                    articlePicture = articlePictures[i];
                } else {
                    articlePicture += "," + articlePictures[i];
                }
            }
        }
        article.setArticlePicture(articlePicture);
        article.setArticleId(articleId);
        int i = articleMapper.updateByPrimaryKeySelective(article);
        if (i > 0) {
            modelAndView.addObject("msg", "文章修改成功");
        } else {
            modelAndView.addObject("msg", "文章修改失败");
        }
        modelAndView.addObject("returnUrl", "website/article");
        return modelAndView;
    }

    /**
     * 文章删除
     *
     * @param request
     * @return
     */
    @RequestMapping("article/delete")
    @ArchivesLog(operationDescription = "删除文章")
    public ModelAndView delArticle(HttpServletRequest request) {
        String[] articleId = request.getParameterValues("articleId");
        int i = 0;
        for (String id : articleId) {
            i += articleMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == articleId.length) {
            modelAndView.addObject("msg", "文章删除成功");
        } else {
            modelAndView.addObject("msg", "文章删除失败");
        }
        modelAndView.addObject("returnUrl", "website/article");
        return modelAndView;
    }

    /**
     * 文章上传
     *
     * @param multipartRequeste
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("article/ajaxFileUpload")
    public @ResponseBody String checkArticleName(MultipartHttpServletRequest multipartRequeste, HttpServletResponse response) throws IOException {

        Iterator<Map.Entry<String,MultipartFile>> it =  multipartRequeste.getFileMap().entrySet().iterator();
        String articlePicture = "";
        while(it.hasNext()){
            MultipartFile BrandPicturempf = it.next().getValue();
            articlePicture =  super.uploadPicsWithoutCompressSize(BrandPicturempf, multipartRequeste, null, null);
        }

        return articlePicture;

    }

    /**
     * 广告位列表
     *
     * @return
     */
    @RequestMapping("ad")
    public ModelAndView advPostionList(HttpServletRequest request){
        String apName = request.getParameter("apName");
        // 改页处理用
        String start = request.getParameter("start");

        AdvPositionBean positionBean = new AdvPositionBean();
        positionBean.setApName(apName);
        // 改页处理时
        if (start != null && !"".equals(start)) {
            positionBean.setStart(Integer.valueOf(start));
        }

        List list = adMapper.selectByCondition(positionBean);
        positionBean.setResultList(list);

        ModelAndView modelAndView =new ModelAndView("website/advert/positionList");
        modelAndView.addObject("page", positionBean);
        return modelAndView;
    }

    /**
     * 广告位增加
     *
     * @return
     */
    @RequestMapping("ad/toAddPostion")
    public ModelAndView advPostionAdd() {
        ModelAndView modelAndView = new ModelAndView("website/advert/positionAdd");

        return modelAndView;
    }

    @RequestMapping("ad/doAddPostion")
    @ArchivesLog(operationDescription = "新增广告位")
    public ModelAndView addAdvPostion(MultipartHttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        AdvPosition advPosition = new AdvPosition();
        advPosition.setApName(request.getParameter("apName"));
        advPosition.setApIntro(request.getParameter("apIntro"));
        Short apClass = Short.valueOf(request.getParameter("apClass"));
        advPosition.setApClass(apClass);
        advPosition.setApDisplay(Short.valueOf(request.getParameter("apDisplay")));
        advPosition.setIsUse(Short.valueOf(request.getParameter("isUse")));
        advPosition.setApWidth(0);
        advPosition.setApHeight(0);
        advPosition.setApPrice(0);
        advPosition.setAdvNum(0);
        advPosition.setClickNum(0);
        // 0图片 1文字 2幻灯 3Flash
        if(apClass == 0 || apClass == 3){
            advPosition.setApWidth(Integer.valueOf(request.getParameter("apWidth")));
            advPosition.setApHeight(Integer.valueOf(request.getParameter("apHeight")));
            MultipartFile default_pic = request.getFile("default_pic");
            if(default_pic != null && default_pic.getOriginalFilename() != null && !"".equals(default_pic.getOriginalFilename())){
                int extIndex = default_pic.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  default_pic.getOriginalFilename().substring(extIndex);
                }
                // 图片文件后缀的判断
                if (!".PNG".equals(extName.toUpperCase()) && !".GIF".equals(extName.toUpperCase()) &&
                        !".JPG".equals(extName.toUpperCase()) && !".JPEG".equals(extName.toUpperCase())) {
                    modelAndView.addObject("msg", "图片文件格式不正确，请选择正确的图片!");
                    modelAndView.addObject("returnUrl", "website/ad");
                    return modelAndView;
                }
                String name = new Date().getTime() + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin,name);
                try {
                    default_pic.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                    advPosition.setDefaultContent(name);
                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("msg", "保存文件失败!");
                    modelAndView.addObject("returnUrl", "website/ad");
                    return modelAndView;
                }
            }
        } else if("1".equals(request.getParameter("apClass"))) {
            advPosition.setAdvNum(Integer.valueOf(request.getParameter("advNum")));
            advPosition.setDefaultContent(request.getParameter("defaultContent"));
        } else {
            //  2的情况处理暂无
        }
        advPosition.setChannel(request.getParameter("channel"));

        int i = adMapper.insertSelective(advPosition);
        if (i > 0) {
            modelAndView.addObject("msg", "广告位新增成功");
        } else {
            modelAndView.addObject("msg", "广告位新增失败");
        }
        modelAndView.addObject("returnUrl", "website/ad");
        return modelAndView;
    }

    /**
     * 广告位修改
     *
     * @return
     */
    @RequestMapping("ad/toModifyPostion")
    public ModelAndView advPostionModify(int apId) {
        ModelAndView modelAndView = new ModelAndView("website/advert/positionEdit");
        AdvPosition advPosition = adMapper.selectByPrimaryKey(apId);
        modelAndView.addObject("advPosition",advPosition);
        return modelAndView;
    }

    @RequestMapping("ad/doModifyPostion")
    @ArchivesLog(operationDescription = "修改广告位")
    public ModelAndView modifyAdvPostion(MultipartHttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        AdvPosition advPosition = new AdvPosition();
        advPosition.setApId(Integer.valueOf(request.getParameter("apId")));
        advPosition.setApName(request.getParameter("apName"));
        advPosition.setApIntro(request.getParameter("apIntro"));
        Short apClass = Short.valueOf(request.getParameter("apClass"));
        advPosition.setApClass(apClass);
        advPosition.setApDisplay(Short.valueOf(request.getParameter("apDisplay")));
        advPosition.setIsUse(Short.valueOf(request.getParameter("isUse")));
        advPosition.setApWidth(0);
        advPosition.setApHeight(0);
        advPosition.setApPrice(0);
        advPosition.setAdvNum(0);
        advPosition.setClickNum(0);
        // 0图片 1文字 2幻灯 3Flash
        if(apClass == 0 || apClass == 3){
            advPosition.setApWidth(Integer.valueOf(request.getParameter("apWidth")));
            advPosition.setApHeight(Integer.valueOf(request.getParameter("apHeight")));
            MultipartFile default_pic = request.getFile("default_pic");
            if(default_pic != null && default_pic.getOriginalFilename() != null && !"".equals(default_pic.getOriginalFilename())){
                int extIndex = default_pic.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  default_pic.getOriginalFilename().substring(extIndex);
                }
                // 图片文件后缀的判断
                if (!".PNG".equals(extName.toUpperCase()) && !".GIF".equals(extName.toUpperCase()) &&
                        !".JPG".equals(extName.toUpperCase()) && !".JPEG".equals(extName.toUpperCase())) {
                    modelAndView.addObject("msg", "图片文件格式不正确，请选择正确的图片!");
                    modelAndView.addObject("returnUrl", "website/ad");
                    return modelAndView;
                }
                String name = new Date().getTime() + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin,name);
                try {
                    default_pic.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                    advPosition.setDefaultContent(name);
                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("msg", "保存文件失败!");
                    modelAndView.addObject("returnUrl", "website/ad");
                    return modelAndView;
                }
            }
        } else if("1".equals(request.getParameter("apClass"))) {
            advPosition.setAdvNum(Integer.valueOf(request.getParameter("advNum")));
            advPosition.setDefaultContent(request.getParameter("defaultContent"));
        } else {
            //  2的情况处理暂无
        }
        advPosition.setChannel(request.getParameter("channel"));
        int i = adMapper.updateByPrimaryKey(advPosition);;
        if (i > 0) {
            modelAndView.addObject("msg", "广告位修改成功");
        } else {
            modelAndView.addObject("msg", "广告位修改失败");
        }
        modelAndView.addObject("returnUrl", "website/ad");
        return modelAndView;
    }

    /**
     * 广告位删除
     *
     * @param request
     * @return
     */
    @RequestMapping("ad/deletePostion")
    @ArchivesLog(operationDescription = "删除广告位")
    public ModelAndView delAdvPostion(HttpServletRequest request) {
        String[] apId = request.getParameterValues("apIds");
        int i = 0;
        for (String id : apId) {
            // 先删除关联的广告，再删除广告位
            advMapper.deleteByPosition(Integer.parseInt(id));
            i += adMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == apId.length) {
            modelAndView.addObject("msg", "广告位删除成功");
        } else {
            modelAndView.addObject("msg", "广告位删除失败");
        }
        modelAndView.addObject("returnUrl", "website/ad");
        return modelAndView;
    }

    /**
     * 广告列表
     *
     * @return
     */
    @RequestMapping("ad/advList")
    public ModelAndView advertList(HttpServletRequest request){
        String apId = request.getParameter("apId");
        String advTitle = request.getParameter("advTitle");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        // 改页处理用
        String start = request.getParameter("start");

        AdvBean advBean = new AdvBean();

        // 从广告位一览页面跳转时可以取得apId
        if (apId != null && !apId.isEmpty()) {
            request.getSession().setAttribute("apId", apId);
        } else {
            // 从信息提示页面返回时，取不到apId
            apId = request.getSession().getAttribute("apId").toString();
        }

        advBean.setApId(Integer.parseInt(apId));
        advBean.setAdvTitle(advTitle);
        if(startTime != null && !startTime.equals("")){
            int advStartTime = DateUtil.toUnixTimeStampByDate(startTime);
            advBean.setAdvStartTime(advStartTime);
            advBean.setStartTime(startTime);
        }
        if(endTime != null && !endTime.equals("")){
            int advEndTime = DateUtil.toUnixTimeStampByDate(endTime);
            advBean.setAdvEndTime(advEndTime);
            advBean.setEndTime(endTime);
        }
        // 改页处理时
        if (start != null && !"".equals(start)) {
            advBean.setStart(Integer.valueOf(start));
        }
        List list = advMapper.selectByCondition(advBean);
        advBean.setResultList(list);

        ModelAndView modelAndView =new ModelAndView("website/advert/advertList");
        modelAndView.addObject("page", advBean);

        AdvPosition position = adMapper.selectByPrimaryKey(advBean.getApId());
        modelAndView.addObject("ad",position);
        return modelAndView;
    }

    /**
     * 广告增加
     *
     * @param apId 广告位ID
     * @return
     */
    @RequestMapping("ad/toAddAdv")
    public ModelAndView advertAdd(int apId) {
        ModelAndView modelAndView = new ModelAndView("website/advert/advertAdd");
        AdvPosition advPosition = adMapper.selectByPrimaryKey(apId);
        modelAndView.addObject("advPosition",advPosition);
        // 新增的广告的排序
        modelAndView.addObject("slideSort", advMapper.selectNextSort());
        return modelAndView;
    }

    @RequestMapping("ad/doAddAdv")
    @ArchivesLog(operationDescription = "新增广告")
    public ModelAndView addAdvert(MultipartHttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        Adv adv = new Adv();
        adv.setApId(Integer.valueOf(request.getParameter("apId")));
        adv.setAdvTitle(request.getParameter("advTitle"));
        // AdvContent
        if("0".equals(request.getParameter("apClass"))||"3".equals(request.getParameter("apClass"))){
            MultipartFile adv_pic = request.getFile("adv_pic");
            if(adv_pic!=null && adv_pic.getOriginalFilename()!=null && !"".equals(adv_pic.getOriginalFilename())){
                int extIndex = adv_pic.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  adv_pic.getOriginalFilename().substring(extIndex);
                }
                // 图片文件后缀的判断
                if (!".PNG".equals(extName.toUpperCase()) && !".GIF".equals(extName.toUpperCase()) &&
                        !".JPG".equals(extName.toUpperCase()) && !".JPEG".equals(extName.toUpperCase())) {
                    modelAndView.addObject("msg", "图片文件格式不正确，请选择正确的图片!");
                    modelAndView.addObject("returnUrl", "website/ad/advList");
                    return modelAndView;
                }
                String name = new Date().getTime() + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin,name);
                try {
                    adv_pic.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                    adv.setAdvContent(name);
                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("msg", "保存文件失败!");
                    modelAndView.addObject("returnUrl", "website/ad/advList");
                    return modelAndView;
                }
            }
        } else if("1".equals(request.getParameter("apClass"))) {
            adv.setAdvContent(request.getParameter("advContent"));
        } else {
            //  2的情况处理暂无
        }
        int advStartTime = DateUtil.toUnixTimeStampByDate(request.getParameter("adv_start_time"));
        int advEndTime = DateUtil.toUnixTimeStampByDate(request.getParameter("adv_end_time"));
        adv.setAdvStartDate(advStartTime);
        adv.setAdvEndDate(advEndTime);
        adv.setSlideSort(Integer.valueOf(request.getParameter("slideSort")));
        adv.setAdvUrl(request.getParameter("advUrl"));

        int i = advMapper.insertSelective(adv);
        if (i > 0) {
            modelAndView.addObject("msg", "广告新增成功");
        } else {
            modelAndView.addObject("msg", "广告新增失败");
        }
        modelAndView.addObject("returnUrl", "website/ad/advList");
        return modelAndView;
    }

    /**
     * 广告修改
     *
     * @return
     */
    @RequestMapping("ad/toModifyAdv")
    public ModelAndView advertModify(int apId,int advId) {
        ModelAndView modelAndView = new ModelAndView("website/advert/advertEdit");
        AdvPosition advPosition = adMapper.selectByPrimaryKey(apId);
        Adv adv = advMapper.selectByPrimaryKey(advId);
        List advList = adMapper.selectByCondition(new AdvPositionBean());
        modelAndView.addObject("advPosition",advPosition);
        modelAndView.addObject("advList",advList);
        modelAndView.addObject("adv",adv);
        return modelAndView;
    }

    @RequestMapping("ad/doModifyAdv")
    @ArchivesLog(operationDescription = "修改广告")
    public ModelAndView modifyAdvert(MultipartHttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        Adv adv = new Adv();
        adv.setAdvId(Integer.valueOf(request.getParameter("advId")));
        adv.setApId(Integer.valueOf(request.getParameter("apId")));
        adv.setAdvTitle(request.getParameter("advTitle"));
        // AdvContent
        if("0".equals(request.getParameter("apClass"))||"3".equals(request.getParameter("apClass"))){
            MultipartFile adv_pic = request.getFile("adv_pic");
            if(adv_pic!=null && adv_pic.getOriginalFilename()!=null && !"".equals(adv_pic.getOriginalFilename())){
                int extIndex = adv_pic.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  adv_pic.getOriginalFilename().substring(extIndex);
                }
                // 图片文件后缀的判断
                if (!".PNG".equals(extName.toUpperCase()) && !".GIF".equals(extName.toUpperCase()) &&
                        !".JPG".equals(extName.toUpperCase()) && !".JPEG".equals(extName.toUpperCase())) {
                    modelAndView.addObject("msg", "图片文件格式不正确，请选择正确的图片!");
                    modelAndView.addObject("returnUrl", "website/ad/advList");
                    return modelAndView;
                }
                String name = new Date().getTime() + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin,name);
                try {
                    adv_pic.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                    adv.setAdvContent(name);
                } catch (IOException e) {
                    e.printStackTrace();
                    modelAndView.addObject("msg", "保存文件失败!");
                    modelAndView.addObject("returnUrl", "website/ad/advList");
                    return modelAndView;
                }
            } else {
                // 未修改图片的情况
                adv.setAdvContent(request.getParameter("advContent"));
            }
        } else if("1".equals(request.getParameter("apClass"))) {
            adv.setAdvContent(request.getParameter("advContent"));
        } else {
            //  2的情况处理暂无
        }
        int advStartTime = DateUtil.toUnixTimeStampByDate(request.getParameter("adv_start_time"));
        int advEndTime = DateUtil.toUnixTimeStampByDate(request.getParameter("adv_end_time"));
        adv.setAdvStartDate(advStartTime);
        adv.setAdvEndDate(advEndTime);
        adv.setSlideSort(Integer.valueOf(request.getParameter("slideSort")));
        adv.setAdvUrl(request.getParameter("advUrl"));

        int i = advMapper.updateByPrimaryKey(adv);
        if (i > 0) {
            modelAndView.addObject("msg", "广告修改成功");
        } else {
            modelAndView.addObject("msg", "广告修改失败");
        }
        modelAndView.addObject("returnUrl", "website/ad/advList");

        return modelAndView;
    }

    /**
     * 广告删除
     *
     * @param request
     * @return
     */
    @RequestMapping("ad/deleteAdv")
    @ArchivesLog(operationDescription = "删除广告")
    public ModelAndView deleteAdvert(HttpServletRequest request) {
        // 图片、flash的场合，删除文件服务器上的文件
        String apId = request.getParameter("apId");
        String[] advId = request.getParameterValues("advId");
        int i = 0;
        for (String id : advId) {
            i += advMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == advId.length) {
            modelAndView.addObject("msg", "广告删除成功");
        } else {
            modelAndView.addObject("msg", "广告删除失败");
        }
        modelAndView.addObject("returnUrl", "website/ad/advList");
        return modelAndView;
    }
}